package popcount

// pc[i] is the population count of i.
var pc [256]byte

func init() {
	for i := range pc {
		pc[i] = pc[i/2] + byte(i&1)
	}
}

// PopCount returns the population count (number of set bits) of x.
func PopCount(x uint64) int {
	ans := int(pc[byte(x>>(0*8))] +
		pc[byte(x>>(1*8))] +
		pc[byte(x>>(2*8))] +
		pc[byte(x>>(3*8))] +
		pc[byte(x>>(4*8))] +
		pc[byte(x>>(5*8))] +
		pc[byte(x>>(6*8))] +
		pc[byte(x>>(7*8))])
	return ans
}

// 用移位方法统计 1 的个数，每次测试最右边的1bit
func PopCountShift(x uint64) int {
	cnt := 0
	for x != 0 {
		if x&1 == 1 {
			cnt++
		}
		x >>= 1
	}
	return cnt
}
